<template>
  <div class="container-plan">
    <div class="Dateblock">
      <div>
        <span class="demonstration">选择计划月份: </span>
        <el-date-picker
          v-model="valueDate"
          type="month"
          placeholder="选择月"
          @change="changeDate">
        </el-date-picker>
      </div>
      <div class="remindDiv">
        <el-tooltip class="item" effect="dark" content="每天下午6点提醒且之后自动创建空白计划" placement="top">
        <span>是否开启计划提醒:</span>
        </el-tooltip>
        <el-switch class="switch-remind"
          active-color="#13ce66"
          v-model="switchRemind"
          @change="switchChange">
        </el-switch>
      </div>

    </div>
    <el-card class="box-card plan-card">
      <div class="block">
        <el-timeline>
          <el-timeline-item
            :key="item.id"
            v-for="item in tasks"
            :timestamp="item.createTime | dateFormat"
            placement="top"
            :color="today === item.createDate ? '#0bbd87' : ''"
          >
            <el-card>
              <div slot="header" class="clearfix">
                <span>YourPlan</span>
                <div>
                  <el-button type="danger" size="mini" round @click="deletePlanData(item.Id)">删除</el-button>
                  <el-button type="primary" size="mini" round @click="showEditPlan(item)">编辑</el-button>
                </div>
              </div>
              <!-- 计划内容显示 -->
              <div v-html="item.planContent"></div>
            </el-card>
          </el-timeline-item>

          <el-timeline-item
            placement="top"
          >
            <el-card class="addPlanCard">
              <div slot="header" class="clearfix">
                <span>YourPlan</span>
              </div>
              <div class="addBtn">
                <!-- 计划内容显示 -->
              <el-button type="primary" @click="displayDialog">添加计划</el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
    <el-card class="box-card">
      <div id="echarts1" class="echarts1" style="width: 900px;height:450px;"></div>
    </el-card>
    <el-card class="box-card">
      <div id="echarts2" class="echarts2" style="width: 900px;height:450px;"></div>
    </el-card>

    <!--添加计划对话框-->
    <el-dialog
      title="添加计划"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      @closed="closeDialog"
    >
      <div id="content">
        <el-form ref="planFormRef" :rules="rules" :model="planForm" :inline="true" size="mini" label-width="80px">
          <el-form-item label="今日学习时间" label-width="150px" prop="studyTime">
            <el-input v-model="planForm.studyTime" type="number"></el-input>
          </el-form-item>
          <el-form-item label="今日运动时间" label-width="150px" prop="sportTime">
            <el-input v-model="planForm.sportTime" type="number"></el-input>
          </el-form-item>
          <!-- 富文本编辑 -->
          <quill-editor v-model="planForm.planContent"></quill-editor>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="info" @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="addPlan">提 交</el-button>
      </span>
    </el-dialog>

    <!--编辑计划对话框-->
    <el-dialog
      title="编辑计划"
      :visible.sync="editDialogVisible"
      width="700px"
      :close-on-click-modal="false"
      @closed="closeDialog"
    >
      <div id="content">
        <el-form ref="planFormRef" :model="planForm" :inline="true" size="mini" label-width="80px">
          <el-form-item label="今日学习时间" label-width="100px" prop="studyTime">
            <el-input v-model="planForm.studyTime" type="number"></el-input>
          </el-form-item>
          <el-form-item label="今日运动时间" label-width="100px">
            <el-input v-model="planForm.sportTime" type="number" prop="sportTime"></el-input>
          </el-form-item>
          <!-- 富文本编辑 -->
          <quill-editor v-model="planForm.planContent"></quill-editor>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="info" @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="editPlan">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入 echarts
import echarts from 'echarts'
import _ from 'lodash'
export default {
  data() {
    var validateStudyTime = (rule, value, callback) => {
      var reg = new RegExp(
        '^\\d{0,2}$'
      ) // 正则表达式
      if (value === '') {
        // 输入不能为空
        callback(new Error('请输入学习时间'))
        return false
      } else if (!reg.test(value)) {
        // 正则验证不通过，格式不对
        callback(new Error('请输入至多两位数字，且小于24'))
        return false
      } else {
        callback()
      }
    }
    var validateSportTime = (rule, value, callback) => {
      var reg = new RegExp(
        '^\\d{0,3}$'
      ) // 正则表达式
      if (value === '') {
        // 输入不能为空
        callback(new Error('请输入运动时间'))
        return false
      } else if (!reg.test(value)) {
        // 正则验证不通过，格式不对
        callback(new Error('请输入至多3位数字，且小于360'))
        return false
      } else {
        callback()
      }
    }
    return {
      // 后台获取的任务内容
      tasks: [],
      // 添加对话框
      dialogVisible: false,
      // 编辑对话框
      editDialogVisible: false,
      // 表单提交的数据
      planForm: {
        id: '',
        studyTime: '',
        sportTime: '',
        planContent: ''
      },
      rules: {
        studyTime: [
          { validator: validateStudyTime, required: true, trigger: 'blur' }
        ],
        sportTime: [
          { validator: validateSportTime, required: true, trigger: 'blur' }
        ]
      },
      // 图标固定内容
      options1: {
        title: {
          text: '每月学习时间(小时)'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '学习时间',
          type: 'line'
        }]
      },
      options2: {
        title: {
          text: '每月运动时间(分钟)'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '运动时间',
          type: 'line'
        }]
      },
      // 选择当前日期
      valueDate: '',
      // 是否开启提醒
      switchRemind: false
    }
  },
  created() {
    this.valueDate = this.toMonth
    this.getPlans()
    this.switchStatus()
    console.log(this.valueDate)
  },
  mounted() {
    this.getChartsData()
  },
  methods: {
    displayDialog() {
      this.dialogVisible = true
    },
    addPlan() {
      // 正式提交之前需要验证
      this.$refs.planFormRef.validate(async valid => {
        if (!valid) return
        // 执行提交操作
        const { data: res } = await this.$http.post('/plan/insertPlan', this.planForm)

        if (res.meta.status !== 200) {
          return this.$message.error('添加计划失败')
        }

        this.dialogVisible = false
        this.$message.success('添加计划成功')
        this.getPlans()
        this.getChartsData()
      })
    },
    async getPlans() {
      const { data: res } = await this.$http.get('/plan/getPlan/' + this.valueDate)

      if (res.meta.status !== 200) {
        return this.$message.error('获取计划列表失败')
      }

      this.tasks = res.data
      console.log(this.tasks)
    },
    showEditPlan(planData) {
      this.planForm.studyTime = planData.studyTime
      this.planForm.sportTime = planData.sportTime
      this.planForm.planContent = planData.planContent
      this.planForm.id = planData.Id
      console.log(this.planForm)
      console.log(planData)
      this.editDialogVisible = true
    },
    closeDialog() {
      this.$refs.planFormRef.resetFields()
      this.planForm.sportTime = ''
      this.planForm.studyTime = ''
      this.planForm.planContent = ''
    },
    resetForm() {
      this.$refs.planFormRef.resetFields()
    },
    // 修改计划操作
    editPlan() {
      // 正式提交之前需要验证
      this.$refs.planFormRef.validate(async valid => {
        if (!valid) return
        // 执行提交操作
        const { data: res } = await this.$http.put('/plan/edit', this.planForm)

        if (res.meta.status !== 200) {
          return this.$message.error('修改计划失败')
        }

        this.editDialogVisible = false
        this.$message.success('修改计划成功')
        this.getPlans()
        // 还需要重新获取一次图标数据
        this.getChartsData()
      })
    },
    // 删除计划
    async deletePlanData(planId) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该计划,是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 如果用户确认删除,则返回字符串confirm
      // 如果用户取消删除,则返回字符串cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 调用api进行删除操作
      const { data: res } = await this.$http.delete('plan/delete/' + planId)

      if (res.meta.status !== 200) {
        return this.$message.error('删除计划失败')
      }

      this.$message.success('删除计划成功')
      this.getPlans()
      this.getChartsData()
    },
    // 获取图表数据
    async getChartsData() {
      // 基于准备好的dom，初始化echarts实例
    // var myChart = echarts.init(document.getElementById('echarts'));
    // 第二个参数可以指定前面引入的主题
      var chart1 = echarts.init(document.getElementById('echarts1'), 'macarons')
      var chart2 = echarts.init(document.getElementById('echarts2'), 'macarons')

      const { data: res1 } = await this.$http.get('/plan/charts/study/' + this.valueDate)
      if (res1.meta.status !== 200) {
        return this.$message.error('获取图表数据失败')
      }

      const resultStudy = _.merge(res1.data, this.options1)

      const { data: res2 } = await this.$http.get('/plan/charts/sport/' + this.valueDate)
      if (res2.meta.status !== 200) {
        return this.$message.error('获取图表数据失败')
      }

      const resultSport = _.merge(res2.data, this.options2)

      // 使用刚指定的配置项和数据显示图表。
      // myChart.setOption(option)
      chart1.setOption(resultStudy)

      chart2.setOption(resultSport)
    },
    // 监听日期变化
    changeDate() {
      console.log('日期已改变')
      this.valueDate = this.getDateString(this.valueDate)
      this.getPlans()
      this.getChartsData()
    },
    // 把日期变为字符串
    getDateString(date) {
    // 获取当前日期
      const dt = new Date(date)

      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      return `${y}-${m}`
    },
    // 监听是否开启计划监听
    async switchChange() {
      const { data: res } = await this.$http.post('/remind', { isOpen: this.switchRemind })
      if (res.meta.status !== 200) {
        return this.$message.error('操作失败')
      }
      this.$message.success('操作成功')
    },
    // 获取用户开关状态
    async switchStatus() {
      const { data: res } = await this.$http.get('/remind')
      if (res.meta.status !== 200) {
        return this.$message.error('获取开关状态失败')
      }
      if (res.data.isOpen === 1) {
        this.switchRemind = true
      } else {
        this.switchRemind = false
      }
    }
  },
  computed: {
    today() {
      // 获取当前日期
      const dt = new Date()

      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      const d = (dt.getDate() + '').padStart(2, '0')
      return `${y}-${m}-${d}`
    },
    toMonth() {
      // 获取当前日期
      const dt = new Date()

      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      return `${y}-${m}`
    }
  }
}
</script>

<style lang="less" scoped>
@import '../../plugins/timeline/timeline.css';
@import '../../plugins/timeline-item/timeline-item.css';
.container-plan {
    width: 100%;
    // position: absolute;
    // left: 10%;
    // margin-left: 100px;
    // padding: 20px;
    background-color: #909399;
    display: flex;
    flex-direction: column;
    align-items: center;
    // overflow: auto;
}

.remindDiv{
  display: flex;
  align-items: center;
}

.box-card {
  width: 1000px;
  height: 600px;
  margin-bottom: 15px;
}

.plan-card {
  overflow: auto;
  background-color: #DCDFE6;
  .el-card__body {
  height: 100%;
  box-sizing: border-box;
  }
}

.clearfix{
  display: flex;
  justify-content: space-between;
}

.bi {
  font-size: x-large;
}

.echarts1{
    margin-top: 70px;
    margin-left: 40px;
}

.echarts2{
    margin-top: 70px;
    margin-left: 40px;
}

.addPlanCard{
  .addBtn{
    text-align: center;
  }
}

// 日期宽度
.Dateblock {
  width: 1000px;
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.switch-remind {
  margin-left: 5px;
}
</style>
